package com.hsbc.manager.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hsbc.entity.Admin;
import com.hsbc.manager.service.AdminService;

@Controller
public class HomeController {
	
	@Autowired
	AdminService adminService;

	@RequestMapping({"/","/index"})
	public String index() {
		return "/index";
	}
	
	@RequestMapping(value="/test",method=RequestMethod.GET)
	@ResponseBody
	public Admin test() throws Exception{
		return adminService.findAdminByUsername("huwei");
	}
	
	@RequestMapping(value="/test1",method=RequestMethod.GET)
	public void test1() {
		adminService.addAdmin1();
	}
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login() {
		return "/login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String ajaxLogin(Admin admin,HttpSession session) {
		JSONObject jsonObject = new JSONObject();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
        try {
            subject.login(token);
//            mobile.addAttribute("name", "admin");
//            mobile.addAttribute("age", "18");
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("msg", "登录成功");

            session.setAttribute("username", admin.getUsername());
            session.setAttribute("password", admin.getPassword());
           
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密码错误");
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (subject.isAuthenticated()){
              return "redirect:/index";
		} else {
			token.clear();
			return "/login";
		}
	}
	
	@RequestMapping(value = "/unauth")
	@ResponseBody
    public Object unauth() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "1000000");
        map.put("msg", "未登录");
        return map;
    }
}
